<template>
  <el-card>
    <div class="toolbar">
      <el-select
        v-model="selectedStoreId"
        placeholder="选择门店"
        filterable
        style="width: 220px"
        @change="fetchAddresses"
      >
        <el-option
          v-for="s in stores"
          :key="s.id"
          :label="s.name"
          :value="s.id"
        />
      </el-select>

      <el-button
        type="primary"
        size="small"
        :disabled="!selectedStoreId"
        @click="openDialog()"
      >
        <el-icon><Plus /></el-icon> 新增地址
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="!multiple.length"
        @click="onBatchDelete"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="addresses"
      stripe
      @selection-change="multiple = $event"
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" />

      <el-table-column align="center" prop="id" label="ID" width="80" />
      <el-table-column align="center" prop="region" label="省市区" />
      <el-table-column align="center" prop="detail" label="详细地址" />

      <el-table-column label="默认" width="120">
        <template #default="{ row }">
          <el-switch
            :model-value="row.isDefault"
            :active-value="1"
            :inactive-value="0"
            size="small"
            @change="(val) => onToggleDefault(row, val)"
            :disabled="row._toggling"
          />
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="createdAt"
        label="创建时间"
        width="180"
      />
      <el-table-column
        align="center"
        prop="updatedAt"
        label="更新时间"
        width="180"
      />

      <el-table-column align="center" label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="openDialog(row)">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button type="text" size="small" @click="onDelete(row)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="请选择门店" />
      </template>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper, sizes, total"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item label="省市区" prop="region">
          <el-input v-model="form.region" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" />
        </el-form-item>
        <el-form-item label="默认地址" prop="isDefault">
          <el-switch
            v-model="form.isDefault"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="saving">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  pageAddresses,
  listByStore,
  createAddress,
  updateAddress,
  deleteAddresses,
} from "@/api/storeAddresses";
import { pageStores } from "@/api/stores";
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 门店下拉
const stores = ref([]);
const selectedStoreId = ref(null);

// 地址列表
const addresses = ref([]);
const loading = ref(false);
const multiple = ref([]);

// 分页
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 弹窗 & 表单
const dialogVisible = ref(false);
const isCreate = ref(true);
const dialogTitle = ref("新增地址");
const form = reactive({
  id: null,
  storeId: null,
  region: "",
  detail: "",
  isDefault: 0,
});
const formRef = ref(null);
const saving = ref(false);

// 校验
const rules = {
  region: [{ required: true, message: "请输入省市区", trigger: "blur" }],
  detail: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
};

async function fetchStores() {
  const res = await pageStores({ pageNum: 1, pageSize: 100 });
  stores.value = res.data.items;
}

function fetchAddresses() {
  if (!selectedStoreId.value) return;
  loading.value = true;
  listByStore(selectedStoreId.value)
    .then((res) => {
      addresses.value = res.data;
      total.value = res.data.length;
    })
    .finally(() => (loading.value = false));
}

function openDialog(row) {
  if (!selectedStoreId.value) return;
  if (row) {
    isCreate.value = false;
    dialogTitle.value = "编辑地址";
    Object.assign(form, { ...row, storeId: selectedStoreId.value });
  } else {
    isCreate.value = true;
    dialogTitle.value = "新增地址";
    Object.assign(form, {
      id: null,
      storeId: selectedStoreId.value,
      region: "",
      detail: "",
      isDefault: 0,
    });
  }
  dialogVisible.value = true;
}

function onSubmit() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    saving.value = true;
    const api = isCreate.value ? createAddress(form) : updateAddress(form);
    api
      .then(() => {
        ElMessage.success(isCreate.value ? "新增成功" : "更新成功");
        dialogVisible.value = false;
        fetchAddresses();
      })
      .finally(() => (saving.value = false));
  });
}

function onDelete(row) {
  ElMessageBox.confirm("确认删除？", "提示", { type: "warning" })
    .then(() => deleteAddresses([row.id].join(",")))
    .then(() => {
      ElMessage.success("删除成功");
      fetchAddresses();
    });
}

function onBatchDelete() {
  ElMessageBox.confirm("确认批量删除？", "提示", { type: "warning" })
    .then(() => deleteAddresses(multiple.value.map((i) => i.id).join(",")))
    .then(() => {
      ElMessage.success("删除成功");
      multiple.value = [];
      fetchAddresses();
    });
}

function onToggleDefault(row, val) {
  // 1. 立刻置灰，防止重复点击
  row._toggling = true;

  // 2. 调用更新接口，只更新 isDefault 字段
  updateAddress({
    id: row.id,
    storeId: selectedStoreId.value,
    region: row.region,
    detail: row.detail,
    isDefault: val,
  })
    .then(() => {
      ElMessage.success(val === 1 ? "已设为默认" : "取消默认");
      fetchAddresses();
      row.isDefault = val;
    })
    .catch(() => {
      // 回滚
      row.isDefault = val === 1 ? 0 : 1;
      ElMessage.error("更新失败，请重试");
    })
    .finally(() => {
      row._toggling = false;
    });
}

onMounted(() => {
  fetchStores();
  fetchAddresses();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
  align-items: center;
}
.pagination {
  text-align: right;
  margin-top: 12px;
}
</style>
